#!/usr/local/bin/python
# -*- coding: utf-8 -*-
from django.shortcuts import render_to_response
from assoce.bibli.models import *
from assoce.core.models import Emprunt, Membre, Item, Activite
from django.http import HttpResponseRedirect, HttpResponse
from datetime import datetime
from django.forms.models import modelform_factory
from django.views.generic.simple import direct_to_template

from django.contrib.auth.decorators import login_required

@login_required
def index(request, group=None, template='bibli/index.html'):
    membre = Membre.objects.get(user=request.user)
    emprunts = Emprunt.objects.filter(membre=membre, end__isnull=True)
    activite_bd = Activite.objects.get(label='BD')
    
    context = {'emprunts':emprunts}
    fields = ['start',]
    
    if activite_bd.is_manager(request.user):
        context['manager'] = True
        fields.append('membre')
        context['sortis'] = Emprunt.objects.filter(end__isnull=True, item__activite=activite_bd)

    form = modelform_factory(model=Emprunt, fields=fields)
    
    if request.method == 'POST':
        form = form(request.POST)
        res = []
        if request.POST.has_key('search'):
            s = request.POST['search_str']
            q = Livre.objects.filter(ref__icontains=s)
            res = list(q)
            q = Livre.objects.filter(item__label__icontains=s)
            res.append(list(q))
            q = Livre.objects.filter(serie__label__icontains=s)
            res.append(list(q))
        if request.POST.has_key('action'):
            if request.POST['action'] == u'Réserver':
                _reserver(request.POST, form)
                return HttpResponseRedirect('')
        context.update({'form':form, 'livres':res})
    else:
        data = {'membre':request.user.id, 'start': datetime.now()}
        context.update({'form':form(data)})
    #return render_to_response(template, context)
    return direct_to_template(request, template, extra_context=context)

def retour(req, id):
    id = int(id)
    
    activite_bd = Activite.objects.get(label='BD')
    if not activite_bd.is_manager(req.user):
        raise Exception("Seul le manager BD peut enregistrer un retour")
    emp = Emprunt.objects.get(id=id)
    if not emp.end:
        emp.end = datetime.now()
        emp.save()
        req.user.message_set.create(message='Le retour a été enregistré correctement.')
    return HttpResponseRedirect('../../#sortis')
    
def _reserver(post, emprunt_form):
    emprunt_form.is_valid()
    data = emprunt_form.cleaned_data
    for k,value in post.iteritems():
        if value == 'on':
            try:
                id = int(k)
                l = Livre.objects.get(item__id=id)
                e = Emprunt(**data)
                e.item = l.item
                e.save()
            except Exception, v:
                raise
    return

from django.views.decorators.cache import cache_page
import django.views.generic.list_detail

@cache_page(60 * 15)
def cached_object_list(request, queryset, paginate_by=None, page=None):
    return django.views.generic.list_detail.object_list(request, queryset, paginate_by, page)

from assoce.core.stats import *
class barchart:
    def __init__(self, name, value, size):
        self.name=name
        self.value=value
        self.size = size
_monthLabels = ['None', 'Janvier', u'Février', 'Mars', 'Avril', 'Mai', 'Juin',
                'Juillet', u'Août', 'Septembre', 'Octobre', 'Novembre', u'Décembre']

@cache_page(3600*5)
def stats(request, template):
    context = {}
    mois07 = []
    curmois = datetime.now().month
    curyear = datetime.now().year
    for m in range(1, curmois+1):
        v = get_nb_emprunts(activite='BD', year=curyear, month=m)
        mois07.append(barchart(_monthLabels[m], v, v*5))
    
    an_list = []
    for a in range(2002, curyear):
        v = get_nb_emprunts(activite='BD', year=a)
        an_list.append(barchart(a, v, v))
    
    context = {'mois_list':mois07, 'an_list':an_list}
    
    context['top10'] = get_top_series(nb=10)
    context['top10n'] = get_top_series(nb=10, normalize=True)
    context['year'] = curyear
    return direct_to_template(request, template, extra_context=context)

def get_top_series(year=None, nb=3, normalize=False):
    if not year: year = datetime.now().year
    q = Emprunt.objects.filter(item__activite__label='BD', start__year=year)
    dseries = {}
    for e in q:
        s = e.item.livre.serie
        if not dseries.has_key(s.id): dseries[s.id] = {'ob':s, 'nb':1}
        else: dseries[s.id]['nb'] += 1
    if normalize:
        for id, item in dseries.iteritems():
            nbtomes = Livre.objects.filter(serie=item['ob']).count()
            item['nb'] = item['nb'] * 10 / nbtomes
    l = list(dseries.itervalues())
    l.sort(key=lambda d: d['nb'], reverse=True)
    return l[:nb]
    